/*
 * @Author: new-wang
 * @Date: 2025-08-27 14:58:13
 * @LastEditors: new-wang
 * @LastEditTime: 2025-08-27 15:01:53
 * @FilePath: \nest-demo\src\common\filters\http-exceptions-filter.ts
 * @Description: 全局使用异常过滤器
 */
import {
  Catch,
  HttpException,
  ExceptionFilter,
  ArgumentsHost,
  HttpStatus,
} from '@nestjs/common'

@Catch(HttpException)
export class HttpExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const status = exception.getStatus()
    // const status =
    //   exception instanceof HttpException
    //     ? exception.getStatus()
    //     : HttpStatus.INTERNAL_SERVER_ERROR;
    //exception.getStatus();
    const exceptionResponse = exception.getResponse()
    let message = exceptionResponse.message ?? 'Service Error'

    if (exceptionResponse?.message instanceof Array) {
      message = exceptionResponse.message[0]
    }

    response.status(200).json({
      code: status,
      msg: message,
      data: null,
      timestamp: new Date().toISOString()
    })
  }
}
